package com.hdl.design.pattern;

import java.util.Scanner;

/**
 * 类名 SimpleFactoryDemo003
 * 描述 需要使用简单工厂，第一个需要优化的例子
 * 题目：控制台上输入两个数字和一个运算符，在控制台打印结果
 *  分析：SimpleFactoryDemo002程序问题如下：
 *  1、上面的程序确实可以正常运行
 *  2、如果用面向对象的思想来做呢
 *  如下改进：
 *
 * @author hedonglin
 * @version 1.0
 * @date 2019/9/6 21:59
 */
public class SimpleFactoryDemo003 {

    public static void main(String[] args) throws Exception {

        System.out.println("请输入数字A:");
        Scanner scanner = new Scanner(System.in);
        double num1 = scanner.nextDouble();

        System.out.println("请输入运算符:");
        scanner = new Scanner(System.in);
        String operate = scanner.next();

        System.out.println("请输入数字B:");
        scanner = new Scanner(System.in);
        double num2 = scanner.nextDouble();

        double result = Operate.getResult(num1, num2, operate);

        System.out.println("结果是：" + result);
    }


    public static class Operate{
        public static double getResult(double num1, double num2, String operate) throws Exception {
            double result;
            switch (operate) {
                case "+":
                    result = num1 + num2;
                    break;
                case "-":
                    result = num1 - num2;
                    break;
                case "*":
                    result = num1 * num2;
                    break;
                case "/":
                    if (num2 != 0) {
                        result = num1 / num2;
                    } else {
                        throw new Exception("除数不能为零");
                    }
                    break;
                default:
                    result = 0.0;
                    break;

            }
                return result;
        }
    }

}
